package com.meiyou.controller;

import com.meiyou.constant.MessageConstant;
import com.meiyou.exception.FileUpFail;
import com.meiyou.result.Result;
import com.meiyou.vo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @BelongsProject: meiyou
 * @BelongsPackage: com.meiyou.controller
 * @Author: 尹晓安
 * @Date: 2023/11/25 17:20
 * @Description: todo
 */
@RestController
@RequestMapping("/api/common")
@Slf4j
public class CommonController {

    @Value("${my.up-image.path}")
    private String basePath;

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<FileVo> upload(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(basePath);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new FileUpFail(MessageConstant.UPLOAD_FAILED);
        }

        FileVo fileVo = FileVo.builder()
                .url(fileName)
                .build();

        return Result.success(fileVo);
    }

    /**
     * 查看图片
     * @param response
     * @param name
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) {

        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            log.error(e.toString());
        }


    }
}
